package configs

import (
	"errors"
	"fmt"
	"github.com/kataras/iris/v12"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"strings"
)

func GetIrisYAMLConfig(configName string) iris.Configurator {
	config := iris.WithConfiguration(iris.YAML(configName))
	return config
}

type CommonConfigModel struct {
	WebApi ConsulServiceConfig `yaml:webapi`
	Consul string        `yaml:consul`
	Grpc   ConsulServiceConfig `yaml:grpc`
}

type ConsulServiceConfig struct {
	Host string `yaml:"host"`
	Port int    `yaml:"port"`
	Name string `yaml:"name"`
}

func GetYAMLConfig(configFile string) (cfg map[string]interface{}, err error) {
	yamlFile, err := ioutil.ReadFile(configFile)
	if err != nil {
		fmt.Printf("failed to read yaml file : %v\n", err)
		return
	}

	err = yaml.Unmarshal(yamlFile, &cfg)
	if err != nil {
		fmt.Printf("failed to unmarshal : %v\n", err)
		return
	}
	return
}
//按照.分割层级循环获取config
//keys eg my.address
func GetConfig(cfg map[string]interface{},keys string) (r interface{},err error) {
	splitKeys:=strings.Split(keys,".")
	if len(splitKeys)==0{
		err=errors.New("empty keys")
		return
	}
	if len(splitKeys)==1{
		r=cfg[splitKeys[0]]
		return
	}
	if cfg[splitKeys[0]]==nil{
		return nil,errors.New("not found")
	}
	conf:=cfg[splitKeys[0]].(map[interface{}]interface{})
	for i,key:=range splitKeys{
		if i==0 {
			continue
		}
		if i==len(splitKeys)-1{
			r=conf[key]
		}else {
			conf=conf[key].(map[interface{}]interface{})
			if conf==nil{
				return nil,errors.New("not found")
			}
		}
	}
	return
}

func GetRedisDefault() string {
	cfg,err:=GetYAMLConfig("./config.yml")
	if err!=nil{
		fmt.Println(err)
	}
	r,_:=GetConfig(cfg,"redis.default")
	return r.(string)
}
func GetDbDefault() string {
	cfg,err:=GetYAMLConfig("./config.yml")
	if err!=nil{
		fmt.Println(err)
	}
	r,_:=GetConfig(cfg,"mysql.default")
	return r.(string)
}
func GetServerPort() int {
	cfg,err:=GetYAMLConfig("./config.yml")
	if err!=nil{
		fmt.Println(err)
	}
	r,_:=GetConfig(cfg,"port")
	return r.(int)
}
